﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.Suspension;
using StyleMVVM.View;
using StyleMVVM.View.Regions;
#if !DOT_NET
using Windows.Foundation;

#endif

namespace StyleMVVM.ViewModel
{
	public class NavigatingViewModel : BaseViewModel, INavigationViewModel
	{
		private string syncKey = null;
		protected bool attemptToSyncOnLeave = true;
		protected bool attemptToResumeOnNavigate = true;

		public virtual object NavigationParameter { get; set; }

		public virtual string SyncKey
		{
			get
			{
				if (syncKey == null && NavigationParameter != null)
				{
					syncKey = NavigationParameter.ToString();
				}

				return syncKey;
			}
			set { syncKey = value; }
		}

		public void NavigatedTo(object sender, StyleNavigationEventArgs e)
		{
#if !WINDOWS_PHONE
			NavigationParameter = e.Parameter;
#endif

			if (attemptToResumeOnNavigate)
			{
				string tempKey = SyncKey;

				if (!string.IsNullOrEmpty(tempKey))
				{
					SyncService.Instance.ResumeWithContext(this, tempKey);
				}
				else
				{
					SyncService.Instance.Resume(this);
				}
			}

			OnNavigatedTo(sender, e);
		}

		public void NavigatedFrom(object sender, StyleNavigationEventArgs e)
		{
			OnNavigatedFrom(sender, e);
		}

#if NETFX_CORE
		public IAsyncAction NavigatingFrom(object sender, StyleNavigatingCancelEventArgs e)
		{
			return InternalNavigatingFrom(sender, e).AsAsyncAction();
		}
#else
		public Task NavigatingFrom(object sender, StyleNavigatingCancelEventArgs e)
		{
			return InternalNavigatingFrom(sender, e);
		}
#endif

		protected virtual async Task InternalNavigatingFrom(object sender, StyleNavigatingCancelEventArgs e)
		{
			await OnNavigatingFrom(sender, e);

			if (!e.Cancel && attemptToSyncOnLeave)
			{
				string tempKey = SyncKey;

				if (!string.IsNullOrEmpty(tempKey))
				{
					SyncService.Instance.SyncWithContext(this, SyncKey);
				}
				else
				{
					SyncService.Instance.Sync(this);
				}
			}
		}

		protected virtual void OnNavigatedTo(object sender, StyleNavigationEventArgs e)
		{
		}

		protected virtual void OnNavigatedFrom(object sender, StyleNavigationEventArgs e)
		{
		}

		protected virtual async Task OnNavigatingFrom(object sender, StyleNavigatingCancelEventArgs e)
		{
		}
	}
}